<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\QuizRequest;
use App\Models\Quiz;
use App\Models\Group;
use App\Http\Resources\Quiz as QuizResource;
use App\Http\Resources\QuizFull as QuizFullResource;
use App\Http\Resources\User as UserResource;
use App\Http\Resources\Bet as BetResource;
use App\Repositories\QuizRepository;
use App\Repositories\GroupRepository;
use App\Repositories\MessageRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * @resource 竞猜
 * Class QuizController
 * @package App\Http\Controllers\Api
 */
class QuizController extends Controller
{

    /**
     * 俱乐部竞猜列表
     *
     * @param Group $group
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function listInGroup(Group $group)
    {
        return QuizResource::collection($group->quizzesWithCreater()->orderBy('created_at', 'DESC')->paginate());
    }

    /**
     * 我的竞猜列表
     *
     * @param QuizRepository $quizRepository
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function list(QuizRepository $quizRepository)
    {
        return QuizResource::collection($quizRepository->findCurrentUserQuizzes());
    }

    /**
     * 可以创建竞猜的俱乐部列表
     *
     * @param Request $request
     * @param GroupRepository $groupRepository
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function canCreateQuizGroups(Request $request, GroupRepository $groupRepository)
    {
        $data = $groupRepository->findGroupsWhichCanCreateQuizByUser($request->user());
        return \App\Http\Resources\Group::collection($data);
    }

    /**
     * 竞猜详情
     *
     * @param Quiz $quiz
     * @return QuizFullResource
     */
    public function show(Quiz $quiz)
    {
        return new QuizFullResource($quiz);
    }

    /**
     * 创建竞猜
     *
     * @param Quiz $quiz
     * @param QuizRequest $request
     * @throws \Exception
     */
    public function create(Quiz $quiz, QuizRequest $request)
    {
        $group = $this->authorizeGroup($request);
        $quiz->fill($request->all())->saveOrFail();
        if (!empty($request->items)) {
            $quiz->items()->createMany($request->items);
        }
        $group->increment('quizzes_count');
        $group->removeCache();

        // todo: 发送模板消息
        if ($request->form_id) {
            MessageRepository::sendCreateQuizMessage($quiz, $request->form_id);
        }

        return new QuizResource($quiz);
    }

    /**
     * 修改竞猜
     *
     * @param Quiz $quiz
     * @param QuizRequest $request
     */
    public function modify(Quiz $quiz, QuizRequest $request)
    {
        $this->authorizeGroup($request);
        $oldStopAt = $quiz->stop_at;
        $quiz->fill($request->all())->saveOrFail();

        // 如果下注时间修改，则取消原先的消息推送，重新发送一条
        if ($oldStopAt !== format_datetime_with_second($quiz->stop_at)) {
            MessageRepository::cancelSendMessage($quiz);
            if ($request->form_id) {
                MessageRepository::sendCreateQuizMessage($quiz, $request->form_id);
            }
        }
    }

    /**
     * 关闭竞猜
     *
     * @param Quiz $quiz
     */
    public function close(Quiz $quiz)
    {
        $quiz->status = QuizRepository::QUIZ_STATUS_CLOSED;
        $quiz->saveOrFail();
        \App\Jobs\CloseQuiz::dispatch($quiz);
        MessageRepository::cancelSendMessage($quiz);
    }

    /**
     * 竞猜参与人列表
     *
     * @param Quiz $quiz
     */
    public function player(Quiz $quiz)
    {
        return UserResource::collection($quiz->players()->paginate());
    }

    /**
     * 投注结果
     *
     * @param Quiz $quiz
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function result(Quiz $quiz)
    {
        return BetResource::collection(
            $quiz->finishedBets()
                ->orderByDesc(DB::raw('user_id = ?'))
                ->addBinding(\request()->user()->id, 'order')
                ->paginate()
        );
    }

    /**
     * @param $request
     * @return mixed
     */
    private function authorizeGroup($request)
    {
        $group = $request instanceof Group
            ? $request : Group::findOrFail($request->group_id);
        $this->authorize('createQuiz', $group);
        return $group;
    }
}
